<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="前端,D3,函数库," />





  <link rel="alternate" href="/atom.xml" title="Zhanmin's blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.2" />






<meta name="description" content="本文的内容是博主在学习D3.js时在配合查阅资料及官方文档所积累的使用D3基本方式与方法。">
<meta property="og:type" content="article">
<meta property="og:title" content="D3.js学习笔记">
<meta property="og:url" content="http://yoursite.com/2017/08/14/D3.js学习笔记/index.html">
<meta property="og:site_name" content="Zhanmin's blog">
<meta property="og:description" content="本文的内容是博主在学习D3.js时在配合查阅资料及官方文档所积累的使用D3基本方式与方法。">
<meta property="og:image" content="http://yoursite.com/./update-exit-enter.png">
<meta property="og:image" content="http://yoursite.com/./event.png">
<meta property="og:image" content="http://yoursite.com/./layout.png">
<meta property="og:updated_time" content="2017-10-16T08:10:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="D3.js学习笔记">
<meta name="twitter:description" content="本文的内容是博主在学习D3.js时在配合查阅资料及官方文档所积累的使用D3基本方式与方法。">
<meta name="twitter:image" content="http://yoursite.com/./update-exit-enter.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2017/08/14/D3.js学习笔记/"/>


  <title> D3.js学习笔记 | Zhanmin's blog </title>
</head>

<body itemscope itemtype="//schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="//schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Zhanmin's blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">拾金之路</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="//schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                D3.js学习笔记
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2017-08-14T10:18:29+08:00" content="2017-08-14">
              2017-08-14
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/blog/" itemprop="url" rel="index">
                    <span itemprop="name">blog</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文的内容是博主在学习D3.js时在配合查阅资料及官方文档所积累的使用D3基本方式与方法。</p>
<a id="more"></a>
<h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><h4 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>D3全称（Data-Driven Documents）：被数据驱动的文档，实际是一个JavaScript的函数库。</p>
</li>
<li><p>选择集：d3.select()或d3.selectAll()选择元素后返回对象</p>
</li>
<li><p>链式语法：D3可以连续不断地调用函数，形如：d3.select().selectAll().text()…</p>
<p>​</p>
</li>
</ul>
<h4 id="选择元素和绑定数据"><a href="#选择元素和绑定数据" class="headerlink" title="选择元素和绑定数据"></a>选择元素和绑定数据</h4><ul>
<li><p>在D3中，用于选择元素的函数有两个：</p>
<ul>
<li>d3.select（）：是选择所有指定元素的第一个；</li>
<li>d3.selectAll（）： 是选择指定元素的全部；</li>
</ul>
<p>返回的结果称为<strong>选择集</strong></p>
</li>
<li><p>D3中，绑定数据的函数有如下两个：</p>
<ul>
<li>datum（）：绑定一个数据到选择集上；</li>
<li>data（）：绑定一个数组到选择集上，数组的各项值分别于选择集的各元素绑定</li>
</ul>
</li>
</ul>
<h4 id="选择、插入、删除元素"><a href="#选择、插入、删除元素" class="headerlink" title="选择、插入、删除元素"></a>选择、插入、删除元素</h4><ul>
<li><p>选择元素</p>
<p>例子：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>Apple<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"myClass"</span> <span class="attr">id</span>=<span class="string">"second"</span>&gt;</span>Pear<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"myClass"</span>&gt;</span>Banana<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div></pre></td></tr></table></figure>
<ul>
<li><p>选择第一个p元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p1 = d3.select(<span class="string">"body"</span>).select(<span class="string">"p"</span>);</div></pre></td></tr></table></figure>
</li>
<li><p>选择三个p元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p2 = d3.select(<span class="string">"body"</span>).selectAll(<span class="string">"p"</span>);</div></pre></td></tr></table></figure>
</li>
<li><p>选择第二个p元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p3 = d3.select(<span class="string">"body"</span>).select(<span class="string">"#second"</span>)</div></pre></td></tr></table></figure>
</li>
<li><p>选择后两个p元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p4 = d3.select(<span class="string">"body"</span>).select(<span class="string">".myClass"</span>)</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>插入元素</p>
<ul>
<li><p>append（）：在选择集末尾插入元素；</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//在body的末尾添加一个p元素</span></div><div class="line">body.append(<span class="string">"p"</span>).text(<span class="string">"append a p element"</span>);</div></pre></td></tr></table></figure>
</li>
<li><p>insert（）：在选择集前面插入元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//在body中id为second的元素前添加一个段落元素</span></div><div class="line">body.insert(<span class="string">"p"</span>,<span class="string">"#second"</span>).text(<span class="string">"insert a p element"</span>);</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>删除元素</p>
<p>删除一个元素时，对于选择的元素，使用remove方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p = body.select(<span class="string">"#second"</span>);</div><div class="line">p.remove();</div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="绘制图表"><a href="#绘制图表" class="headerlink" title="绘制图表"></a>绘制图表</h3><h4 id="基本概念-1"><a href="#基本概念-1" class="headerlink" title="基本概念"></a>基本概念</h4><p>HTML5提供两种强有力的“画布”：SVG和Canvas</p>
<ul>
<li>SVG（Scalable Vector Graphics）：可缩放矢量图形，用于描述二维矢量图形的一种图形格式，是由万维网联盟制定的开放标准。SVG使用XML格式来定义图形，除了IE8之前的版本外，绝大部分浏览器都支持SVG，可将SVG文本直接嵌入HTML中显示。SVG有如下特点：<ul>
<li>SVG绘制的是矢量图，因此对图像进行放大不会失真；</li>
<li>基于XML，可以为每个元素添加JavaScript事件处理器；</li>
<li>每个图形均视为对象，更改对象的属性，图形也会改变；</li>
<li>不适合游戏应用。</li>
</ul>
</li>
<li>Canvas：是通过JavaScript来绘制2D图形，是HTML5中新增的元素，它有如下特点：<ul>
<li>绘制的是位图，图像放大后会失真；</li>
<li>不支持事件处理器；</li>
<li>能够以.png或.jpg格式保存图像；</li>
<li>适合游戏应用</li>
</ul>
</li>
</ul>
<h4 id="SVG画布的预定义元素"><a href="#SVG画布的预定义元素" class="headerlink" title="SVG画布的预定义元素"></a>SVG画布的预定义元素</h4><ul>
<li>六种基本图形：<ul>
<li>矩形</li>
<li>圆形</li>
<li>椭圆</li>
<li>线段</li>
<li>折现</li>
<li>多边形</li>
</ul>
</li>
<li>一种特殊图形<ul>
<li>路径</li>
</ul>
</li>
</ul>
<h4 id="绘制方法"><a href="#绘制方法" class="headerlink" title="绘制方法"></a>绘制方法</h4><ul>
<li><p>添加画布</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> width =<span class="number">300</span>;</div><div class="line"><span class="keyword">var</span> height = <span class="number">300</span>;</div><div class="line"></div><div class="line"><span class="keyword">var</span> svg = d3.select(<span class="string">"body"</span>).append(<span class="string">"svg"</span>).attr(<span class="string">"width"</span>,width).attr(<span class="string">"height"</span>,height);</div></pre></td></tr></table></figure>
</li>
<li><p>绘制矩形</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">svg</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">rect</span>&gt;</span><span class="tag">&lt;/<span class="name">rect</span>&gt;</span></div><div class="line">  	<span class="tag">&lt;<span class="name">rect</span>&gt;</span><span class="tag">&lt;/<span class="name">rect</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">svg</span>&gt;</span></div></pre></td></tr></table></figure>
<p>rect的属性有：</p>
<ul>
<li><p>x ：矩形左上角的x坐标</p>
</li>
<li><p>y ：矩形左上角的y坐标</p>
</li>
<li><p>width：矩形的宽度</p>
</li>
<li><p>height：矩形的高度</p>
<p>（在SVG中，x轴正方向是水平向右，y轴的正方向是垂直向下）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">   <span class="keyword">var</span> width =<span class="number">300</span>;</div><div class="line"><span class="keyword">var</span> height = <span class="number">300</span>;</div><div class="line"><span class="keyword">var</span> rectHeight = <span class="number">25</span>;</div><div class="line"><span class="keyword">var</span> dataset = [<span class="number">250</span>,<span class="number">210</span>,<span class="number">170</span>,<span class="number">130</span>,<span class="number">90</span>,<span class="number">1</span>]</div><div class="line"></div><div class="line"><span class="keyword">var</span> svg = body.append(<span class="string">"svg"</span>).attr(<span class="string">"width"</span>,width).attr(<span class="string">"height"</span>,height);</div><div class="line">svg.selectAll(<span class="string">"rect"</span>) <span class="comment">//选择svg内所有的矩形</span></div><div class="line">.data(dataset)        <span class="comment">//绑定数组</span></div><div class="line">.enter()              <span class="comment">//指定选择集的enter部分</span></div><div class="line">.append(<span class="string">"rect"</span>)       <span class="comment">//添加足够数量的矩形元素</span></div><div class="line">.attr(<span class="string">"x"</span>,<span class="number">20</span>)</div><div class="line">.attr(<span class="string">"y"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">	<span class="keyword">return</span> i * rectHeight;</div><div class="line">&#125;)</div><div class="line">.attr(<span class="string">"width"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">	<span class="keyword">return</span> d;</div><div class="line">&#125;</div><div class="line">.attr(<span class="string">"height"</span>,rectHeight<span class="number">-2</span>)</div><div class="line">.attr(<span class="string">"fill"</span>,<span class="string">"steelblue"</span>);</div></pre></td></tr></table></figure>
<p>​</p>
</li>
</ul>
</li>
</ul>
<h3 id="比例尺"><a href="#比例尺" class="headerlink" title="比例尺"></a>比例尺</h3><h4 id="基本概念-2"><a href="#基本概念-2" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>定义：将某一区域的值映射到另一区域，其大小关系不变——称为比例尺（Scale）。类似于数学中的一元二次函数，有x和y两个未知数，当x的值确定时，y的值也就确定了。在数学中，x的范围被称为<strong>定义域</strong>，y的范围被称为<strong>值域</strong>。D3中的比例尺，分别称为domain和range。</p>
</li>
<li><p>种类（最常用的有以下两种）</p>
<ul>
<li><p>线性比例尺 ——能将一个连续的区间，映射到另一区间。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> dataset = [<span class="number">1.2</span>, <span class="number">2.3</span>, <span class="number">0.9</span>, <span class="number">1.5</span>, <span class="number">3.3</span>];</div><div class="line"><span class="keyword">var</span> min = d3.min(dataset);</div><div class="line"><span class="keyword">var</span> max = d3.max(dataset);</div><div class="line"></div><div class="line"><span class="keyword">var</span> linear = d3.scale.linear()</div><div class="line">        .domain([min, max])</div><div class="line">        .range([<span class="number">0</span>, <span class="number">300</span>]);</div><div class="line"></div><div class="line">linear(<span class="number">0.9</span>);    <span class="comment">//返回 0</span></div><div class="line">linear(<span class="number">2.3</span>);    <span class="comment">//返回 175</span></div><div class="line">linear(<span class="number">3.3</span>);    <span class="comment">//返回 300</span></div></pre></td></tr></table></figure>
<p>其中，d3.scale.linear()返回一个线性比例尺，可以当做<strong>函数</strong>来使用。domain（）和range（）分别设定比例尺的定义域和值域。</p>
</li>
<li><p>序数比例尺——有些定义域和值域是离散的，例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> index = [<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>];</div><div class="line"><span class="keyword">var</span> color = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>, <span class="string">"yellow"</span>, <span class="string">"black"</span>];</div><div class="line"></div><div class="line"><span class="keyword">var</span> ordinal = d3.scale.ordinal()</div><div class="line">			.domain(index)</div><div class="line">			.range(color);</div><div class="line"></div><div class="line">ordinal(<span class="number">0</span>); <span class="comment">//返回 red</span></div><div class="line">ordinal(<span class="number">2</span>); <span class="comment">//返回 green</span></div><div class="line">ordinal(<span class="number">4</span>); <span class="comment">//返回 black</span></div></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h4 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> linear = d3.scale.linear()</div><div class="line">	.domain([d3.min(dataset),d3.max(dataset)])</div><div class="line">	.range([<span class="number">0</span>,<span class="number">250</span>]);</div><div class="line"></div><div class="line">	svg.selectAll(<span class="string">"rect"</span>)</div><div class="line">	.data(dataset)</div><div class="line">	.enter()</div><div class="line">	.append(<span class="string">"rect"</span>)</div><div class="line">	.attr(<span class="string">"x"</span>,<span class="number">20</span>)</div><div class="line">	.attr(<span class="string">"y"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">		<span class="keyword">return</span> i * rectHeight;</div><div class="line">	&#125;)</div><div class="line">	.attr(<span class="string">"width"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">		<span class="keyword">return</span> linear(d);  <span class="comment">//在这里用比例尺</span></div><div class="line">	&#125;)</div><div class="line">	.attr(<span class="string">"height"</span>,rectHeight<span class="number">-2</span>)</div><div class="line">	.attr(<span class="string">"fill"</span>,<span class="string">"steelblue"</span>);</div></pre></td></tr></table></figure>
<h3 id="坐标轴"><a href="#坐标轴" class="headerlink" title="坐标轴"></a>坐标轴</h3><h4 id="基本概念-3"><a href="#基本概念-3" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li>定义：是可视化图表中经常出现的一种图形，由一些线段和刻度组成。坐标轴在SVG中没有现成的图形元素，需要用其他的元素组合构成。D3提供了坐标的组件，如此在SVG画布中绘制坐标轴变得像添加一个普通元素一样简单。</li>
</ul>
<h4 id="定义坐标轴"><a href="#定义坐标轴" class="headerlink" title="定义坐标轴"></a>定义坐标轴</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//数据</span></div><div class="line"><span class="keyword">var</span> dataset = [ <span class="number">2.5</span> , <span class="number">2.1</span> , <span class="number">1.7</span> , <span class="number">1.3</span> , <span class="number">0.9</span> ];</div><div class="line"><span class="comment">//定义比例尺</span></div><div class="line"><span class="keyword">var</span> linear = d3.scale.linear()</div><div class="line">      .domain([<span class="number">0</span>, d3.max(dataset)])</div><div class="line">      .range([<span class="number">0</span>, <span class="number">250</span>]);</div><div class="line"></div><div class="line"><span class="keyword">var</span> axis = d3.svg.axis()</div><div class="line">     .scale(linear)      <span class="comment">//指定比例尺</span></div><div class="line">     .orient(<span class="string">"bottom"</span>)   <span class="comment">//指定刻度的方向</span></div><div class="line">     .ticks(<span class="number">7</span>);          <span class="comment">//指定刻度的数量</span></div></pre></td></tr></table></figure>
<h4 id="在SVG中添加坐标轴"><a href="#在SVG中添加坐标轴" class="headerlink" title="在SVG中添加坐标轴"></a>在SVG中添加坐标轴</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">svg.append(<span class="string">"g"</span>).call(axis); <span class="xml"><span class="tag">&lt;<span class="name">====</span>&gt;</span> axis(svg.append("g"))</span></div></pre></td></tr></table></figure>
<p>call（）的参数是一个函数，调用之后，将当前的选择集作为参数传递给此参数。</p>
<h4 id="设定坐标轴的样式和位置"><a href="#设定坐标轴的样式和位置" class="headerlink" title="设定坐标轴的样式和位置"></a>设定坐标轴的样式和位置</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="css"></span></div><div class="line">	<span class="selector-class">.axis</span> <span class="selector-tag">path</span>,</div><div class="line">	<span class="selector-class">.axis</span> <span class="selector-tag">line</span>&#123;</div><div class="line">		<span class="attribute">fill</span>:none;</div><div class="line">		<span class="attribute">stroke</span>:black;</div><div class="line">		<span class="attribute">shape-rendering</span>:crisoEdges;</div><div class="line">	&#125;</div><div class="line">	<span class="selector-class">.axis</span> <span class="selector-tag">text</span>&#123;</div><div class="line">		<span class="attribute">font-family</span>: sans-serif;</div><div class="line">		<span class="attribute">font-size</span>: <span class="number">11px</span>;</div><div class="line">	&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">javascript</span>&gt;</span></div><div class="line">svg.append("g")</div><div class="line">	.attr("class","axis")</div><div class="line">	.attr("transform","translate(20,130)")</div><div class="line">	.call(axis);</div><div class="line"><span class="tag">&lt;/<span class="name">javascript</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="动态图表"><a href="#动态图表" class="headerlink" title="动态图表"></a>动态图表</h3><h4 id="基本概念-4"><a href="#基本概念-4" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>动态效果——<strong>动态</strong>的图标是指图表在某一时间段会发生某种变化，可能是形状、颜色、位置等，而且是用户可以看到变化的过程的。在D3中称之为<strong>过渡（transition）</strong></p>
<p>​</p>
</li>
</ul>
<h4 id="实现方法"><a href="#实现方法" class="headerlink" title="实现方法"></a>实现方法</h4><ul>
<li><p>transition（）—— 启动过渡效果，其前后是图形变化前后的状态（形状、位置、颜色等）。如下面例子所示：D3 会自动对两种颜色（红色和铁蓝色）之间的颜色值（RGB值）进行插值计算，得到过渡用的颜色值。我们无需知道中间是怎么计算的，只需要享受结果即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">.attr(<span class="string">"fill"</span>,<span class="string">"red"</span>)         <span class="comment">//初始颜色为红色</span></div><div class="line">.transition()               <span class="comment">//启动过渡</span></div><div class="line">.attr(<span class="string">"fill"</span>,<span class="string">"steelblue"</span>)   <span class="comment">//终止颜色为铁蓝色</span></div></pre></td></tr></table></figure>
</li>
<li><p>duration（）—— 指定过渡的持续时间，单位为毫秒。</p>
</li>
<li><p>ease（）—— 指定过渡的方式，调用方式：ease（”bounce”）常用的有：</p>
<ul>
<li>linear：普通的线性变化；</li>
<li>circle：慢慢地到达变换的最终状态；</li>
<li>elastic：带有弹跳地到达最终状态；</li>
<li>bounce：在最终状态处弹跳几次。</li>
</ul>
</li>
<li><p>delay（）——指定延迟的时间，表示一定时间后才开始转变，单位同样为毫秒。此函数可以对整体指定延迟，也可以对个别指定延迟。</p>
<ul>
<li><p>对整体指定：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">.transition()</div><div class="line">.duration(<span class="number">1000</span>)</div><div class="line">.delay(<span class="number">500</span>)</div><div class="line"><span class="comment">//如此，图形整体在延迟 500 毫秒后发生变化，变化的时长为 1000 毫秒。因此，过渡的总时长为1500毫秒。</span></div></pre></td></tr></table></figure>
</li>
<li><p>一个一个图形指定：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">.transition()</div><div class="line">.duration(<span class="number">1000</span>)</div><div class="line">.delay(funtion(d,i)&#123;</div><div class="line">    <span class="keyword">return</span> <span class="number">200</span>*i;</div><div class="line">&#125;)</div><div class="line"><span class="comment">//如此，假设有 10 个元素，那么第 1 个元素延迟 0 毫秒（因为 i = 0），第 2 个元素延迟 200 毫秒，第 3 个延迟 400 毫秒，依次类推….整个过渡的长度为 200 * 9 + 1000 = 2800 毫秒。</span></div></pre></td></tr></table></figure>
<p>​</p>
</li>
</ul>
</li>
</ul>
<h3 id="数据绑定后三种处理方法"><a href="#数据绑定后三种处理方法" class="headerlink" title="数据绑定后三种处理方法"></a>数据绑定后三种处理方法</h3><h4 id="理解update、enter与exit"><a href="#理解update、enter与exit" class="headerlink" title="理解update、enter与exit"></a>理解update、enter与exit</h4><ul>
<li>概念：上述方法一般用来处理的是当选择集和数据的数量关系不确定的情况。</li>
<li>关系：如果数组为 [3, 6, 9, 12, 15]，将此数组绑定到三个 p 元素的选择集上。可以想象，会有两个数据没有元素与之对应，这时候 D3 会建立两个空的元素与数据对应，这一部分就称为 <strong>Enter</strong>。而有元素与数据对应的部分称为 <strong>Update</strong>。如果数组为 [3]，则会有两个元素没有数据绑定，那么没有数据绑定的部分被称为 <strong>Exit</strong>。示意图如下所示</li>
</ul>
<p><img src="./update-exit-enter.png" alt="update-exit-enter"></p>
<h4 id="Update与Enter的使用"><a href="#Update与Enter的使用" class="headerlink" title="Update与Enter的使用"></a>Update与Enter的使用</h4><ul>
<li><p>场景：当对应的元素不足时 （ 绑定数据数量 &gt; 对应元素 ），需要添加元素（append）。</p>
<p>现在 body 中有三个 p 元素，要绑定一个长度大于 3 的数组到 p 的选择集上，然后分别处理 update 和 enter 两部分。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> dataset = [ <span class="number">3</span> , <span class="number">6</span> , <span class="number">9</span> , <span class="number">12</span> , <span class="number">15</span> ];</div><div class="line"></div><div class="line"><span class="comment">//选择body中的p元素</span></div><div class="line"><span class="keyword">var</span> p = d3.select(<span class="string">"body"</span>).selectAll(<span class="string">"p"</span>);</div><div class="line"></div><div class="line"><span class="comment">//获取update部分</span></div><div class="line"><span class="keyword">var</span> update = p.data(dataset);</div><div class="line"></div><div class="line"><span class="comment">//获取enter部分</span></div><div class="line"><span class="keyword">var</span> enter = update.enter();</div><div class="line"></div><div class="line"><span class="comment">//update部分的处理：更新属性值</span></div><div class="line">update.text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="string">"update "</span> + d;</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">//enter部分的处理：添加元素后赋予属性值</span></div><div class="line">enter.append(<span class="string">"p"</span>)</div><div class="line">    .text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"enter "</span> + d;</div><div class="line">    &#125;);</div></pre></td></tr></table></figure>
<ul>
<li>update 部分的处理办法一般是：更新属性值</li>
<li>enter 部分的处理办法一般是：添加元素后，赋予属性值</li>
<li>exit 部分的绝大部分操作是删除</li>
</ul>
</li>
</ul>
<h4 id="Update与Exit的使用"><a href="#Update与Exit的使用" class="headerlink" title="Update与Exit的使用"></a>Update与Exit的使用</h4><ul>
<li><p>场景：当对应的元素过多时 （ 绑定数据数量 &lt; 对应元素 ），需要删掉多余的元素。</p>
<p>现在 body 中有三个 p 元素，要绑定一个长度小于 3 的数组到 p 的选择集上，然后分别处理 update 和 exit 两部分。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> dataset = [ <span class="number">3</span> ];</div><div class="line"></div><div class="line"><span class="comment">//选择body中的p元素</span></div><div class="line"><span class="keyword">var</span> p = d3.select(<span class="string">"body"</span>).selectAll(<span class="string">"p"</span>);</div><div class="line"></div><div class="line"><span class="comment">//获取update部分</span></div><div class="line"><span class="keyword">var</span> update = p.data(dataset);</div><div class="line"></div><div class="line"><span class="comment">//获取exit部分</span></div><div class="line"><span class="keyword">var</span> exit = update.exit();</div><div class="line"></div><div class="line"><span class="comment">//update部分的处理：更新属性值</span></div><div class="line">update.text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="string">"update "</span> + d;</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">//exit部分的处理：修改p元素的属性</span></div><div class="line">exit.text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"exit"</span>;</div><div class="line">    &#125;);</div><div class="line"></div><div class="line"><span class="comment">//exit部分的处理通常是删除元素</span></div><div class="line"><span class="comment">// exit.remove();</span></div></pre></td></tr></table></figure>
<p>​</p>
</li>
</ul>
<h3 id="交互操作"><a href="#交互操作" class="headerlink" title="交互操作"></a>交互操作</h3><h4 id="基本概念-5"><a href="#基本概念-5" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li>定义：交互指的是用户输入了某种指令，程序接受到指令之后必须做出某种响应。对可视化图表来说，交互能使图表更加生动，能表现更多内容。例如，拖动图表中某些图形、鼠标滑到图形上出现提示框，用触屏放大或缩小图形等。</li>
<li>交互的工具：鼠标、键盘、触屏</li>
</ul>
<h4 id="添加交互"><a href="#添加交互" class="headerlink" title="添加交互"></a>添加交互</h4><ul>
<li><p>方法：在D3中，每一个选择集都有on（）函数，用于添加事件监听器</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> circle = svg.append(<span class="string">"circle"</span>);</div><div class="line"></div><div class="line">circle.on(<span class="string">"click"</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">  <span class="comment">//交互内容</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure>
</li>
<li><p>参数：on（）的第一个参数是监听的事件，第二个参数是监听到事件后响应的内容，且为一个函数</p>
</li>
<li><p>鼠标常用的事件：</p>
<ul>
<li>click：鼠标单击某元素时，相当于 mousedown 和 mouseup 组合在一起。</li>
<li>mouseover：光标放在某元素上。</li>
<li>mouseout：光标从某元素上移出来时。</li>
<li>mousemove：鼠标被移动的时候。</li>
<li>mousedown：鼠标按钮被按下。</li>
<li>mouseup：鼠标按钮被松开。</li>
<li>dblclick：鼠标双击。</li>
</ul>
</li>
<li><p>键盘常用的事件：</p>
<ul>
<li>keydown：当用户按下任意键时触发，按住不放会重复触发此事件。该事件不会区分字母的大小写，例如“A”和“a”被视为一致。</li>
<li>keypress：当用户按下字符键（大小写字母、数字、加号、等号、回车等）时触发，按住不放会重复触发此事件。该事件区分字母的大小写。</li>
<li>keyup：当用户释放键时触发，不区分字母的大小写。</li>
</ul>
</li>
<li><p>触屏常用的事件：</p>
<ul>
<li>touchstart：当触摸点被放在触摸屏上时。</li>
<li>touchmove：当触摸点在触摸屏上移动时。</li>
<li>touchend：当触摸点从触摸屏上拿开时。</li>
</ul>
</li>
<li><p>d3.event对象：当某个事件被监听到时，D3 会把当前的事件存到 d3.event 对象，里面保存了当前事件的各种参数。</p>
</li>
</ul>
<p><img src="./event.png" alt="event"></p>
<h3 id="布局-数据转换"><a href="#布局-数据转换" class="headerlink" title="布局(数据转换)"></a>布局(数据转换)</h3><h4 id="基本概念-6"><a href="#基本概念-6" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>布局：决定什么元素绘制在哪里。</p>
</li>
<li><p>D3与其他可视化工具的区别：</p>
<p><img src="./layout.png" alt="layout"></p>
<ul>
<li>选择 D3：如果希望开发脑海中任意想象到的图表。</li>
<li>选择 Highcharts、Echarts 等：如果希望开发几种固定种类的、十分大众化的图表。</li>
</ul>
</li>
<li><p>布局的作用：将<strong>不适合用于绘图的数据</strong>转换成了<strong>适合用于绘图的数据</strong>。</p>
</li>
</ul>
<h4 id="布局的种类"><a href="#布局的种类" class="headerlink" title="布局的种类"></a>布局的种类</h4><ul>
<li>D3提供了12个布局：饼状图（Pie）、力导向图（Force）、弦图（Chord）、树状图（Tree）、集群图（Cluster）、捆图（Bundle）、打包图（Pack）、直方图（Histogram）、分区图（Partition）、堆栈图（Stack）、矩阵树图（Treemap）、层级图（Hierarchy）</li>
<li>12 个布局中，层级图（Hierarchy）不能直接使用。集群图、打包图、分区图、树状图、矩阵树图是由层级图扩展来的。如此一来，能够使用的布局是 11 个（有 5 个是由层级图扩展而来）。这些布局的作用都是将某种数据转换成另一种数据，而转换后的数据是利于可视化的。</li>
</ul>
<h3 id="饼状图"><a href="#饼状图" class="headerlink" title="饼状图"></a>饼状图</h3><h4 id="绘制流程"><a href="#绘制流程" class="headerlink" title="绘制流程"></a>绘制流程</h4><ul>
<li><p>准备数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> dataset = [ <span class="number">30</span> , <span class="number">10</span> , <span class="number">43</span> , <span class="number">55</span> , <span class="number">13</span> ];</div></pre></td></tr></table></figure>
</li>
<li><p>布局（数据转换）—— 计算出适合于作图的数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> pie = d3.layout.pie();</div><div class="line"></div><div class="line"><span class="keyword">var</span> piedata = pie(dataset);</div></pre></td></tr></table></figure>
</li>
<li><p>绘制图形步骤：</p>
<ol>
<li><p>创建弧生成器</p>
<p>为了根据转换后的数据 piedata 来作图，还需要一样工具：生成器。</p>
<p>SVG 有一个元素，叫做路径 path，是 SVG 中功能最强的元素，它可以表示其它任意的图形。顾名思义，路径元素就是通过定义一个段“路径”，来绘制出各种图形。但是，路径是很难计算的，通过布局转换后的数据 piedata 仍然很难手动计算得到路径值。为我们完成这项任务的，就是<strong>生成器</strong>。</p>
<p>这里要用到的叫做<strong>弧生成器</strong>，能够生成弧的路径，因为饼图的每一部分都是一段弧。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> outerRadius = <span class="number">150</span>; <span class="comment">//外半径</span></div><div class="line"><span class="keyword">var</span> innerRadius = <span class="number">0</span>; <span class="comment">//内半径，为0则中间没有空白</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> arc = d3.svg.arc()  <span class="comment">//弧生成器</span></div><div class="line">    .innerRadius(innerRadius)   <span class="comment">//设置内半径</span></div><div class="line">    .outerRadius(outerRadius);  <span class="comment">//设置外半径</span></div><div class="line"><span class="comment">//弧生成器返回的结果赋值给 arc。此时，arc 可以当做一个函数使用，把 piedata 作为参数传入，即可得到路径值。</span></div></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ul>
<ol>
<li><p>添加图形元素</p>
<p>先在 svg 里添加足够数量（5个）个分组元素（g），每一个分组用于存放一段弧的相关元素。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> arcs = d3.select(<span class="string">"body"</span>)</div><div class="line">           .select(<span class="string">"svg"</span>)</div><div class="line">           .attr(<span class="string">"width"</span>,<span class="number">800</span>)</div><div class="line">           .attr(<span class="string">"height"</span>,<span class="number">800</span>)</div><div class="line">           .selectAll(<span class="string">"g"</span>)</div><div class="line">           .data(piedata)</div><div class="line">           .enter()</div><div class="line">           .append(<span class="string">"g"</span>)</div><div class="line">           .attr(<span class="string">"transform"</span>,<span class="string">"translate("</span>+(width/<span class="number">2</span>)+<span class="string">","</span>+(width/<span class="number">2</span>)+<span class="string">")"</span>);</div></pre></td></tr></table></figure>
</li>
<li><p>给每个元素添加path</p>
<p>  因为 arcs 是同时选择了 5 个 g 元素的选择集，所以调用 append(“path”) 后，每个 g 中都有 path 。路径值的属性名称是 d，调用弧生成器后返回的值赋值给它。要注意，arc(d) 的参数 d 是被绑定的数据。</p>
  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> color = d3.scale.category10();   <span class="comment">//有十种颜色的颜色比例尺</span></div><div class="line">arcs.append(<span class="string">"path"</span>)</div><div class="line">    .attr(<span class="string">"fill"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> color(i);</div><div class="line">    &#125;)</div><div class="line">    .attr(<span class="string">"d"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> arc(d);   <span class="comment">//调用弧生成器，得到路径值</span></div><div class="line">    &#125;);</div></pre></td></tr></table></figure>
</li>
<li><p>添加文本</p>
<p>  arc.centroid(d) 能算出弧线的中心。要注意，text() 里返回的是 d.data ，而不是 d 。因为被绑定的数据是对象，里面有 d.startAngle、d.endAngle、d.data 等，其中 d.data 才是转换前的整数的值。</p>
  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">arcs.append(<span class="string">"text"</span>)</div><div class="line">    .attr(<span class="string">"transform"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"translate("</span> + arc.centroid(d) + <span class="string">")"</span>;</div><div class="line">    &#125;)</div><div class="line">    .attr(<span class="string">"text-anchor"</span>,<span class="string">"middle"</span>)</div><div class="line">    .text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> d.data;</div><div class="line">    &#125;);</div></pre></td></tr></table></figure>
<p>  ​</p>
</li>
</ol>
<h3 id="力导向图"><a href="#力导向图" class="headerlink" title="力导向图"></a>力导向图</h3><h4 id="基本概念-7"><a href="#基本概念-7" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>力导向图（Force-Directed Graph），是绘图的一种算法。在二维或三维空间里配置<strong>节点</strong>，节点之间用线连接，称为<strong>连线</strong>。各连线的长度几乎相等，且尽可能不相交。节点和连线都被施加了<strong>力</strong>的作用，力是根据节点和连线的相对位置计算的。根据力的作用，来计算节点和连线的运动轨迹，并不断降低它们的能量，最终达到一种能量很低的安定状态。</p>
</li>
<li><p>作用：力导向图能表示节点之间的多对多的关系。</p>
<p>​</p>
</li>
</ul>
<h4 id="绘制流程-1"><a href="#绘制流程-1" class="headerlink" title="绘制流程"></a>绘制流程</h4><ul>
<li><p>准备数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> nodes = [</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"桂林"</span>&#125;,</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"广州"</span>&#125;,</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"厦门"</span>&#125;,</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"杭州"</span>&#125;,</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"上海"</span>&#125;,</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"青岛"</span>&#125;,</div><div class="line">               &#123;<span class="attr">name</span>:<span class="string">"天津"</span>&#125;</div><div class="line">           ];</div><div class="line"></div><div class="line">           <span class="keyword">var</span> edges = [</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">0</span>, <span class="attr">target</span> :<span class="number">1</span>&#125;,</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">0</span>, <span class="attr">target</span> :<span class="number">2</span>&#125;,</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">0</span>, <span class="attr">target</span> :<span class="number">3</span>&#125;,</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">1</span>, <span class="attr">target</span> :<span class="number">4</span>&#125;,</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">1</span>, <span class="attr">target</span> :<span class="number">5</span>&#125;,</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">1</span>, <span class="attr">target</span> :<span class="number">6</span>&#125;,</div><div class="line">               &#123;<span class="attr">source</span> : <span class="number">0</span>, <span class="attr">target</span> :<span class="number">6</span>&#125;</div><div class="line">           ];</div></pre></td></tr></table></figure>
</li>
<li><p>布局（数据转换）—— 计算出适合于作图的数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> force = d3.layout.force()</div><div class="line">      		.nodes(nodes) <span class="comment">//指定节点数组</span></div><div class="line">      		.links(edges) <span class="comment">//指定连线数组</span></div><div class="line">      		.size([width,height]) <span class="comment">//指定作用域范围</span></div><div class="line">     		.linkDistance(<span class="number">150</span>) <span class="comment">//指定连线长度</span></div><div class="line">     		.charge([<span class="number">-400</span>]); <span class="comment">//相互之间的作用力</span></div><div class="line"></div><div class="line">force.start();    <span class="comment">//开始作用</span></div></pre></td></tr></table></figure>
</li>
<li><p>绘制图形步骤：</p>
<ol>
<li><p>绘制三种图形元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//添加连线</span></div><div class="line"> <span class="keyword">var</span> svg_edges = svg.selectAll(<span class="string">"line"</span>)</div><div class="line">     .data(edges)</div><div class="line">     .enter()</div><div class="line">     .append(<span class="string">"line"</span>)</div><div class="line">     .style(<span class="string">"stroke"</span>,<span class="string">"#ccc"</span>)</div><div class="line">     .style(<span class="string">"stroke-width"</span>,<span class="number">1</span>);</div><div class="line"></div><div class="line"> <span class="keyword">var</span> color = d3.scale.category20();</div><div class="line"></div><div class="line"> <span class="comment">//添加节点</span></div><div class="line"> <span class="keyword">var</span> svg_nodes = svg.selectAll(<span class="string">"circle"</span>)</div><div class="line">     .data(nodes)</div><div class="line">     .enter()</div><div class="line">     .append(<span class="string">"circle"</span>)</div><div class="line">     .attr(<span class="string">"r"</span>,<span class="number">20</span>)</div><div class="line">     .style(<span class="string">"fill"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">         <span class="keyword">return</span> color(i);</div><div class="line">     &#125;)</div><div class="line">     .call(force.drag);  <span class="comment">//使得节点能够拖动</span></div><div class="line"></div><div class="line"> <span class="comment">//添加描述节点的文字</span></div><div class="line"> <span class="keyword">var</span> svg_texts = svg.selectAll(<span class="string">"text"</span>)</div><div class="line">     .data(nodes)</div><div class="line">     .enter()</div><div class="line">     .append(<span class="string">"text"</span>)</div><div class="line">     .style(<span class="string">"fill"</span>, <span class="string">"black"</span>)</div><div class="line">     .attr(<span class="string">"dx"</span>, <span class="number">20</span>)</div><div class="line">     .attr(<span class="string">"dy"</span>, <span class="number">8</span>)</div><div class="line">     .text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">        <span class="keyword">return</span> d.name;</div><div class="line">     &#125;);</div></pre></td></tr></table></figure>
</li>
<li><p>更新节点和连线的位置</p>
<p>力导向图布局 force 有一个事件 tick，每进行到一个时刻，都要调用它，更新的内容就写在它的监听器里就好。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">force.on(<span class="string">"tick"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; <span class="comment">//对于每一个时间间隔</span></div><div class="line">    <span class="comment">//更新连线坐标</span></div><div class="line">    svg_edges.attr(<span class="string">"x1"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.source.x; &#125;)</div><div class="line">        .attr(<span class="string">"y1"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.source.y; &#125;)</div><div class="line">        .attr(<span class="string">"x2"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.target.x; &#125;)</div><div class="line">        .attr(<span class="string">"y2"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.target.y; &#125;);</div><div class="line"></div><div class="line">    <span class="comment">//更新节点坐标</span></div><div class="line">    svg_nodes.attr(<span class="string">"cx"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.x; &#125;)</div><div class="line">        .attr(<span class="string">"cy"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.y; &#125;);</div><div class="line"></div><div class="line">    <span class="comment">//更新文字坐标</span></div><div class="line">    svg_texts.attr(<span class="string">"x"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.x; &#125;)</div><div class="line">       .attr(<span class="string">"y"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123; <span class="keyword">return</span> d.y; &#125;);</div><div class="line"> &#125;);</div></pre></td></tr></table></figure>
<p>​</p>
</li>
</ol>
</li>
</ul>
<h3 id="树状图"><a href="#树状图" class="headerlink" title="树状图"></a>树状图</h3><h4 id="基本概念-8"><a href="#基本概念-8" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>树状图：可表示节点之间的包含于被包含的关系</p>
</li>
<li><p>JSON数据（JavaScript Object Notation）是一种轻量级的数据交换格式，本例中通过读取json文件中的数据来展示树状图。</p>
<p>​</p>
</li>
</ul>
<h4 id="绘制流程-2"><a href="#绘制流程-2" class="headerlink" title="绘制流程"></a>绘制流程</h4><ul>
<li><p>准备数据</p>
<p>以下数据表示“中国-省份名称-城市名称-区县名称”的包含与被包含关系</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line"><span class="attr">"name"</span>:<span class="string">"中国"</span>,</div><div class="line"><span class="attr">"children"</span>:</div><div class="line">[</div><div class="line">    &#123;</div><div class="line">      <span class="attr">"name"</span>:<span class="string">"浙江"</span> ,</div><div class="line">      <span class="attr">"children"</span>:</div><div class="line">      [</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"杭州"</span> &#125;,</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"宁波"</span> &#125;,</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"温州"</span> &#125;,</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"绍兴"</span> &#125;</div><div class="line">      ]</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    &#123;</div><div class="line">        <span class="attr">"name"</span>:<span class="string">"广西"</span> ,</div><div class="line">        <span class="attr">"children"</span>:</div><div class="line">        [</div><div class="line">            &#123;</div><div class="line">            <span class="attr">"name"</span>:<span class="string">"桂林"</span>,</div><div class="line">            <span class="attr">"children"</span>:</div><div class="line">            [</div><div class="line">                &#123;<span class="attr">"name"</span>:<span class="string">"秀峰区"</span>&#125;,</div><div class="line">                &#123;<span class="attr">"name"</span>:<span class="string">"叠彩区"</span>&#125;,</div><div class="line">                &#123;<span class="attr">"name"</span>:<span class="string">"象山区"</span>&#125;,</div><div class="line">                &#123;<span class="attr">"name"</span>:<span class="string">"七星区"</span>&#125;</div><div class="line">            ]</div><div class="line">            &#125;,</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"南宁"</span>&#125;,</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"柳州"</span>&#125;,</div><div class="line">            &#123;<span class="attr">"name"</span>:<span class="string">"防城港"</span>&#125;</div><div class="line">        ]</div><div class="line">    &#125;</div><div class="line">]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>布局（数据转换）—— 计算出适合于作图的数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"> <span class="keyword">var</span> tree = d3.layout.tree()</div><div class="line">                    .size([width,height<span class="number">-200</span>]) <span class="comment">//设定尺寸，即转换后的各节点的坐标在哪一个范围内</span></div><div class="line">                    .separation(<span class="function"><span class="keyword">function</span>(<span class="params">a,b</span>)</span>&#123; <span class="comment">//设定节点之间的间隔</span></div><div class="line">                        <span class="keyword">return</span> (a.parent === b.parent ? <span class="number">1</span> : <span class="number">2</span>);</div><div class="line">                    &#125;);</div><div class="line"></div><div class="line">d3.json(<span class="string">"./data.json"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">error,root</span>)</span>&#123; <span class="comment">//向服务器请求JSON文件</span></div><div class="line">                <span class="keyword">var</span> nodes = tree.nodes(root);<span class="comment">//nodes 中有各个节点的子节点（children）、深度（depth）、名称（name）、位置（x，y）信息，其中名称（name）是 json 文件中就有的属性。</span></div><div class="line">                <span class="keyword">var</span> links = tree.links(nodes);<span class="comment">//links 中有连线两端（ source , target ）的节点信息。</span></div><div class="line">&#125;</div><div class="line">        <span class="comment">//Chrome中禁止访问本地文件，需要搭建网络服务器进行访问，如http-server或Apache</span></div></pre></td></tr></table></figure>
</li>
<li><p>绘制图形步骤：</p>
<ol>
<li><p>创建对角线生成器</p>
<p>D3中提供了绘制函数：d3.svg.diagonal()，即只要输入两个顶点坐标，便可生成一条贝塞尔曲线</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> diagonal = d3.svg.diagonal()</div><div class="line">    .projection(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>) </span>&#123; <span class="keyword">return</span> [d.y, d.x]; &#125;);</div><div class="line"><span class="comment">//projection() 是一个点变换器，默认是 [ d.x , d.y ]，即保持原坐标不变，如果写成 [ d.y , d.x ] ，即是说对任意输入的顶点，都交换 x 和 y 坐标。</span></div></pre></td></tr></table></figure>
</li>
<li><p>绘制连线</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> link = svg.selectAll(<span class="string">".link"</span>)</div><div class="line">      .data(links)</div><div class="line">      .enter()</div><div class="line">      .append(<span class="string">"path"</span>)</div><div class="line">      .attr(<span class="string">"class"</span>, <span class="string">"link"</span>)</div><div class="line">      .attr(<span class="string">"d"</span>, diagonal);   <span class="comment">//使用对角线生成器</span></div></pre></td></tr></table></figure>
</li>
<li><p>绘制节点圆圈和文字</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> node = svg.selectAll(<span class="string">".node"</span>)</div><div class="line">              .data(nodes)</div><div class="line">              .enter()</div><div class="line">              .append(<span class="string">"g"</span>)</div><div class="line">              .attr(<span class="string">"class"</span>,<span class="string">"node"</span>)</div><div class="line">              .attr(<span class="string">"transform"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">                   <span class="keyword">return</span> <span class="string">"translate("</span>+d.y+<span class="string">","</span>+d.x+<span class="string">")"</span>;</div><div class="line">              &#125;);</div><div class="line"></div><div class="line">node.append(<span class="string">"circle"</span>)</div><div class="line">  	.attr(<span class="string">"r"</span>,<span class="number">4.5</span>);</div><div class="line"></div><div class="line">node.append(<span class="string">"text"</span>)</div><div class="line">    .attr(<span class="string">"dx"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">          <span class="keyword">return</span> d.children ? <span class="number">-8</span> : <span class="number">8</span> ;</div><div class="line">    &#125;)</div><div class="line">    .attr(<span class="string">"dy"</span>,<span class="number">3</span>)</div><div class="line">    .style(<span class="string">"text-anchor"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">          <span class="keyword">return</span> d.children ? <span class="string">"end"</span>:<span class="string">"start"</span>;</div><div class="line">    &#125;)</div><div class="line">    .text(<span class="function"><span class="keyword">function</span>(<span class="params">d</span>)</span>&#123;</div><div class="line">          <span class="keyword">return</span> d.name ;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>​</p>
</li>
</ol>
</li>
</ul>
<h3 id="地图"><a href="#地图" class="headerlink" title="地图"></a>地图</h3><h4 id="基本概念-9"><a href="#基本概念-9" class="headerlink" title="基本概念"></a>基本概念</h4><ul>
<li><p>地图：在数据可视化中，地图展示是很重要的一部分，很多情况会与地图有关联，如中国各省的人口多少，GDP多少等，都可以和地图联系在一起。</p>
<p>​</p>
</li>
</ul>
<h4 id="绘制流程-3"><a href="#绘制流程-3" class="headerlink" title="绘制流程"></a>绘制流程</h4><ul>
<li><p>准备数据</p>
<p>地图数据的获取：将JSON个格式应用于地理上的文件，叫做GeoJson文件。中国地图的 GeoJSON 文件： <a href="http://www.ourd3js.com/demo/rm/R-10.0/china.geojson" target="_blank" rel="external">china.geojson</a>。这个文件是用 <a href="http://www.naturalearthdata.com/downloads/" target="_blank" rel="external">Natural Earth</a> 上的数据，经过提取后制作而成，去掉了很多无用的信息，只保留的中国的各省份的名字和 id 号，在这里先感谢 Natural Earth 提供的数据。</p>
</li>
<li><p>投影函数</p>
<p>由于 GeoJSON 文件中的地图数据，都是经度和纬度的信息。它们都是三维的，而要在网页上显示的是二维的，所以要设定一个投影函数来转换经度纬度。如下所示，使用 d3.geo.mercator() 的投影方式。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> projection = d3.geo.mercator()</div><div class="line">                 .center([<span class="number">107</span>,<span class="number">31</span>]) <span class="comment">//设定地图中心位置</span></div><div class="line">                 .scale(<span class="number">850</span>) <span class="comment">//设定放大的比例</span></div><div class="line">                 .translate([width/<span class="number">2</span>,height/<span class="number">2</span>]); <span class="comment">//设定平移</span></div></pre></td></tr></table></figure>
</li>
<li><p>地理路径生成器</p>
<p>为了根据地图的地理数据生成 SVG 中 path 元素的路径值，需要用到 d3.geo.path()，我称它为地理路径生成器。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> path = d3.geo.path()</div><div class="line">    .projection(projection);</div><div class="line"><span class="comment">//projection() 是设定生成器的投影函数，把上面定义的投影传入即可。以后，当使用此生成器计算路径时，会自己加入投影的影响。</span></div></pre></td></tr></table></figure>
</li>
<li><p>向服务器请求文件并绘制地图</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">d3.json(<span class="string">"china.geojson"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">error,root</span>)</span>&#123;</div><div class="line">            <span class="keyword">if</span>(error)&#123;</div><div class="line">                <span class="keyword">return</span> <span class="built_in">console</span>.error(error);</div><div class="line">            &#125;</div><div class="line">            <span class="built_in">console</span>.log(root.features);</div><div class="line">            svg.selectAll(<span class="string">"path"</span>)</div><div class="line">                .data(root.features)</div><div class="line">                .enter()</div><div class="line">                .append(<span class="string">"path"</span>)</div><div class="line">                .attr(<span class="string">"stroke"</span>,<span class="string">"#000"</span>)</div><div class="line">                .attr(<span class="string">"stroke-width"</span>,<span class="number">1</span>)</div><div class="line">                .attr(<span class="string">"fill"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">                    <span class="keyword">return</span> color(i);</div><div class="line">                &#125;)</div><div class="line">                .attr(<span class="string">"d"</span>,path) <span class="comment">//使用地理路径生成器</span></div><div class="line">                .on(<span class="string">"mouseover"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">                    d3.select(<span class="keyword">this</span>).attr(<span class="string">"fill"</span>,<span class="string">"yellow"</span>);</div><div class="line">                &#125;)</div><div class="line">                .on(<span class="string">"mouseout"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">d,i</span>)</span>&#123;</div><div class="line">                    d3.select(<span class="keyword">this</span>).attr(<span class="string">"fill"</span>,color(i));</div><div class="line">                &#125;);</div><div class="line">        &#125;);</div></pre></td></tr></table></figure>
<p>​</p>
</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/前端/" rel="tag">#前端</a>
          
            <a href="/tags/D3/" rel="tag">#D3</a>
          
            <a href="/tags/函数库/" rel="tag">#函数库</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/20/React学习笔记/" rel="next" title="React学习笔记">
                <i class="fa fa-chevron-left"></i> React学习笔记
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/10/14/CSS预处理语言学习笔记/" rel="prev" title="CSS预处理语言学习笔记">
                CSS预处理语言学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="//schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Zhanmin" />
          <p class="site-author-name" itemprop="name">Zhanmin</p>
          <p class="site-description motion-element" itemprop="description">一码年华，瑰宝永留存</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">6</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念"><span class="nav-number">1.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#选择元素和绑定数据"><span class="nav-number">1.2.</span> <span class="nav-text">选择元素和绑定数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#选择、插入、删除元素"><span class="nav-number">1.3.</span> <span class="nav-text">选择、插入、删除元素</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#绘制图表"><span class="nav-number">2.</span> <span class="nav-text">绘制图表</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-1"><span class="nav-number">2.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SVG画布的预定义元素"><span class="nav-number">2.2.</span> <span class="nav-text">SVG画布的预定义元素</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#绘制方法"><span class="nav-number">2.3.</span> <span class="nav-text">绘制方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#比例尺"><span class="nav-number">3.</span> <span class="nav-text">比例尺</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-2"><span class="nav-number">3.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用方法"><span class="nav-number">3.2.</span> <span class="nav-text">使用方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#坐标轴"><span class="nav-number">4.</span> <span class="nav-text">坐标轴</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-3"><span class="nav-number">4.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#定义坐标轴"><span class="nav-number">4.2.</span> <span class="nav-text">定义坐标轴</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在SVG中添加坐标轴"><span class="nav-number">4.3.</span> <span class="nav-text">在SVG中添加坐标轴</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设定坐标轴的样式和位置"><span class="nav-number">4.4.</span> <span class="nav-text">设定坐标轴的样式和位置</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#动态图表"><span class="nav-number">5.</span> <span class="nav-text">动态图表</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-4"><span class="nav-number">5.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#实现方法"><span class="nav-number">5.2.</span> <span class="nav-text">实现方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据绑定后三种处理方法"><span class="nav-number">6.</span> <span class="nav-text">数据绑定后三种处理方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#理解update、enter与exit"><span class="nav-number">6.1.</span> <span class="nav-text">理解update、enter与exit</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Update与Enter的使用"><span class="nav-number">6.2.</span> <span class="nav-text">Update与Enter的使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Update与Exit的使用"><span class="nav-number">6.3.</span> <span class="nav-text">Update与Exit的使用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#交互操作"><span class="nav-number">7.</span> <span class="nav-text">交互操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-5"><span class="nav-number">7.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#添加交互"><span class="nav-number">7.2.</span> <span class="nav-text">添加交互</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#布局-数据转换"><span class="nav-number">8.</span> <span class="nav-text">布局(数据转换)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-6"><span class="nav-number">8.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#布局的种类"><span class="nav-number">8.2.</span> <span class="nav-text">布局的种类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#饼状图"><span class="nav-number">9.</span> <span class="nav-text">饼状图</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#绘制流程"><span class="nav-number">9.1.</span> <span class="nav-text">绘制流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#力导向图"><span class="nav-number">10.</span> <span class="nav-text">力导向图</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-7"><span class="nav-number">10.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#绘制流程-1"><span class="nav-number">10.2.</span> <span class="nav-text">绘制流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#树状图"><span class="nav-number">11.</span> <span class="nav-text">树状图</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-8"><span class="nav-number">11.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#绘制流程-2"><span class="nav-number">11.2.</span> <span class="nav-text">绘制流程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#地图"><span class="nav-number">12.</span> <span class="nav-text">地图</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基本概念-9"><span class="nav-number">12.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#绘制流程-3"><span class="nav-number">12.2.</span> <span class="nav-text">绘制流程</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhanmin</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.2"></script>



  



  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = false;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title >= 0 || index_content >= 0 ){
                                isMatch = true;
								if (i == 0) {
                                    first_occur = index_content;
                                }
                            } 
							
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
